<template>
  <div class="student-statistics-container">
    <div class="title-container">
      <h1>学员信息统计</h1>
      <el-button type="primary" @click="fetchStatistics">刷新数据</el-button>
    </div>

    <el-card v-loading="loading">
      <!-- 总数统计卡片 -->
      <div class="summary-cards">
        <el-card shadow="hover" class="summary-card">
          <div class="summary-number">{{ totalStudents }}</div>
          <div class="summary-title">总学员数</div>
        </el-card>
        <el-card shadow="hover" class="summary-card male-card">
          <div class="summary-number">{{ statistics.maleCount }}</div>
          <div class="summary-title">男生人数</div>
        </el-card>
        <el-card shadow="hover" class="summary-card female-card">
          <div class="summary-number">{{ statistics.femaleCount }}</div>
          <div class="summary-title">女生人数</div>
        </el-card>
      </div>

      <!-- 图表区域 -->
      <el-row :gutter="20">
        <!-- 性别比例饼图 -->
        <el-col :span="12">
          <div ref="genderChart" class="chart-container"></div>
        </el-col>

        <!-- 年龄分布柱状图 -->
        <el-col :span="12">
          <div ref="ageChart" class="chart-container"></div>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="chart-row">
        <!-- 地区分布 -->
        <el-col :span="12">
          <div ref="provinceChart" class="chart-container"></div>
        </el-col>

        <!-- 入学年份分布 -->
        <el-col :span="12">
          <div ref="yearChart" class="chart-container"></div>
        </el-col>
      </el-row>

      <!-- 班级分布 -->
      <el-row>
        <el-col :span="24">
          <div ref="classChart" class="chart-container large-chart"></div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: 'StudentStatistics',
  data() {
    return {
      loading: false,
      statistics: {
        maleCount: 0,
        femaleCount: 0,
        ageGroupStats: {},
        provinceStats: {},
        enrollmentYearStats: {},
        classStats: {}
      },
      // 图表实例
      genderChartInstance: null,
      ageChartInstance: null,
      provinceChartInstance: null,
      yearChartInstance: null,
      classChartInstance: null
    };
  },

  computed: {
    // 计算总学生数
    totalStudents() {
      return this.statistics.maleCount + this.statistics.femaleCount;
    }
  },

  methods: {
    // 获取统计数据
    async fetchStatistics() {
      this.loading = true;
      try {
        // 使用新的API路径
        const response = await axios.get('/api/stats');
        if (response.data.code === 1) {
          this.statistics = response.data.data;
          this.$nextTick(() => {
            this.renderCharts();
          });
        } else {
          this.$message.error(response.data.msg || '获取数据失败');
        }
      } catch (error) {
        this.$message.error('获取数据失败: ' + (error.message || '未知错误'));
        console.error('获取学生统计数据失败', error);
      } finally {
        this.loading = false;
      }
    },

    // 渲染所有图表
    renderCharts() {
      this.renderGenderChart();
      this.renderAgeChart();
      this.renderProvinceChart();
      this.renderYearChart();
      this.renderClassChart();
    },

    // 渲染性别比例饼图
    renderGenderChart() {
      if (!this.genderChartInstance) {
        this.genderChartInstance = echarts.init(this.$refs.genderChart);
      }

      const option = {
        title: {
          text: '性别比例',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['男生', '女生']
        },
        series: [
          {
            name: '性别比例',
            type: 'pie',
            radius: '60%',
            center: ['50%', '50%'],
            data: [
              { value: this.statistics.maleCount, name: '男生' },
              { value: this.statistics.femaleCount, name: '女生' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            },
            color: ['#409EFF', '#F56C6C']
          }
        ]
      };

      this.genderChartInstance.setOption(option);
    },

    // 渲染年龄分布柱状图
    renderAgeChart() {
      if (!this.ageChartInstance) {
        this.ageChartInstance = echarts.init(this.$refs.ageChart);
      }

      const ageData = this.statistics.ageGroupStats || {};
      const ageCategories = Object.keys(ageData);
      const ageValues = ageCategories.map(key => ageData[key]);

      const option = {
        title: {
          text: '年龄段分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ageCategories,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '人数'
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            data: ageValues,
            itemStyle: {
              color: '#67C23A'
            }
          }
        ]
      };

      this.ageChartInstance.setOption(option);
    },

    // 渲染地区分布饼图
    renderProvinceChart() {
      if (!this.provinceChartInstance) {
        this.provinceChartInstance = echarts.init(this.$refs.provinceChart);
      }

      const provinceData = this.statistics.provinceStats || {};
      const provinceItems = Object.keys(provinceData).map(key => {
        return { name: key, value: provinceData[key] };
      });

      const option = {
        title: {
          text: '地区分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
        },
        series: [
          {
            name: '地区分布',
            type: 'pie',
            radius: '55%',
            center: ['40%', '50%'],
            data: provinceItems,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };

      this.provinceChartInstance.setOption(option);
    },

    // 渲染入学年份柱状图
    renderYearChart() {
      if (!this.yearChartInstance) {
        this.yearChartInstance = echarts.init(this.$refs.yearChart);
      }

      const yearData = this.statistics.enrollmentYearStats || {};
      const yearCategories = Object.keys(yearData).sort();
      const yearValues = yearCategories.map(key => yearData[key]);

      const option = {
        title: {
          text: '入学年份分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: yearCategories
        },
        yAxis: {
          type: 'value',
          name: '人数'
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            data: yearValues,
            itemStyle: {
              color: '#E6A23C'
            }
          }
        ]
      };

      this.yearChartInstance.setOption(option);
    },

    // 渲染班级分布条形图
    renderClassChart() {
      if (!this.classChartInstance) {
        this.classChartInstance = echarts.init(this.$refs.classChart);
      }

      const classData = this.statistics.classStats || {};
      const classCategories = Object.keys(classData);
      const classValues = classCategories.map(key => classData[key]);

      const option = {
        title: {
          text: '班级人数分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '人数'
        },
        yAxis: {
          type: 'category',
          data: classCategories,
          axisLabel: {
            interval: 0
          }
        },
        series: [
          {
            name: '人数',
            type: 'bar',
            data: classValues,
            itemStyle: {
              color: '#409EFF'
            }
          }
        ]
      };

      this.classChartInstance.setOption(option);
    },

    // 处理窗口大小变化，重置图表大小
    handleResize() {
      if (this.genderChartInstance) this.genderChartInstance.resize();
      if (this.ageChartInstance) this.ageChartInstance.resize();
      if (this.provinceChartInstance) this.provinceChartInstance.resize();
      if (this.yearChartInstance) this.yearChartInstance.resize();
      if (this.classChartInstance) this.classChartInstance.resize();
    }
  },

  mounted() {
    // 组件挂载后获取数据并初始化图表
    this.fetchStatistics();
    // 添加窗口大小变化监听
    window.addEventListener('resize', this.handleResize);
  },

  beforeDestroy() {
    // 组件销毁前移除事件监听
    window.removeEventListener('resize', this.handleResize);
    // 销毁图表实例
    if (this.genderChartInstance) this.genderChartInstance.dispose();
    if (this.ageChartInstance) this.ageChartInstance.dispose();
    if (this.provinceChartInstance) this.provinceChartInstance.dispose();
    if (this.yearChartInstance) this.yearChartInstance.dispose();
    if (this.classChartInstance) this.classChartInstance.dispose();
  }
};
</script>

<style scoped>
.student-statistics-container {
  padding: 20px;
}

.title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.title-container h1 {
  margin: 0;
  font-size: 24px;
}

.summary-cards {
  display: flex;
  margin-bottom: 20px;
  gap: 20px;
}

.summary-card {
  flex: 1;
  text-align: center;
  padding: 20px;
}

.summary-number {
  font-size: 36px;
  font-weight: bold;
  color: #303133;
}

.summary-title {
  margin-top: 10px;
  color: #606266;
}

.male-card .summary-number {
  color: #409EFF;
}

.female-card .summary-number {
  color: #F56C6C;
}

.chart-container {
  height: 300px;
  margin-bottom: 20px;
}

.large-chart {
  height: 400px;
}

.chart-row {
  margin-top: 20px;
}
</style>
